/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.security.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pmc.dwa.common.utils.Escape;
import com.pmc.dwa.common.utils.Httptear;
import com.pmc.dwa.common.utils.JsonGrid;
import com.pmc.dwa.common.utils.JsonUtils;
import com.pmc.dwa.common.utils.PaginationSupport;
import com.pmc.dwa.common.utils.Util;
import com.pmc.dwa.security.intercept.PmcSecurityMetadataSource;
import com.pmc.dwa.security.model.TGroup;
import com.pmc.dwa.security.model.TRole;
import com.pmc.dwa.security.model.TSect;
import com.pmc.dwa.security.model.TSysoperLog;
import com.pmc.dwa.security.service.IRoleLogService;
import com.pmc.dwa.security.service.ISectionResourceService;
import com.pmc.dwa.security.service.IUserService;

/**
 * @description 角色/日志管理
 * @author aokunsang
 * @date 2013-1-8
 */
@Controller
@RequestMapping("/rbac")
public class RolelogController {

	@Autowired
	private IUserService userService;
	@Autowired
	private IRoleLogService rolelogService;
	@Autowired
	private ISectionResourceService srService;
	final static String DEFAULT_LOG_FIELD = "loginUname-LOGIN_UNAME|operMod-OPER_MOD|operEvent-OPER_EVENT|operIp-OPER_IP|operFrom-OPER_FROM";

/*------------------------------------角色管理-------------------------------------*/
	@RequestMapping(value="getAllRolesList",method={RequestMethod.GET})
	public @ResponseBody List<TRole> getAllRolesList(){
		List<TRole> roles = userService.findAllRoles();
		return roles;
	}
	/* 分页查询角色*/
	@RequestMapping(value="getAllRole",method=RequestMethod.POST)
	public @ResponseBody JsonGrid<TRole> getAllRole(
			@RequestParam(required=true) Integer page,
			@RequestParam(required=true) Integer rows,
			String comments){
		PaginationSupport<TRole> pager = rolelogService.getPagesTRole(comments, page, rows);
		return new JsonGrid<TRole>(pager);
	}
	
	@RequestMapping(value="addRole",method=RequestMethod.POST)
	public @ResponseBody String addRole(TRole role){
		try {
			role.setCreate_time(new Timestamp(System.currentTimeMillis()));
			role.setStatus((byte)1);
			role.setPid(role.getPid());
			if(!StringUtils.isEmpty(role.getRolecode()) && !StringUtils.isEmpty(role.getRolename())){
				role.setRolename(role.getRolecode().toUpperCase()+"_"+role.getRolename().toUpperCase());
			}else{
				role.setRolename("PERM_UNKNOW");
			}
			rolelogService.addRole(role);
			return "{success:true,msg:''}";
		} catch (Exception e) {
			return "{success:false,msg:'"+Escape.escape(e.getMessage())+"'}";
		}
	}
	
	@RequestMapping(value="getRole/{roleid}")
	public @ResponseBody TRole getRole(@PathVariable String roleid){
		TRole role = rolelogService.getRole(roleid);
		if(role==null){
			role = new TRole();
		}else{
			String[] rolenameArr = role.getRolename().split("_");
			role.setRolecode(rolenameArr[0]);
			role.setRolename(rolenameArr[1]);
		}
		return role;
	}
	
	@RequestMapping(value="editRole/{roleid}",method=RequestMethod.POST)
	public @ResponseBody String editRole(@PathVariable int roleid,TRole role){
		try {
			role.setId(roleid);
			role.setUpdate_time(new Timestamp(System.currentTimeMillis()));
			role.setPid(role.getPid());
			role.setRolename(role.getRolecode().toUpperCase()+"_"+role.getRolename().toUpperCase());
			rolelogService.editRole(role);
			return "{success:true,msg:''}";
		} catch (Exception e) {
			return "{success:false,msg:'"+Escape.escape(e.getMessage())+"'}";
		}
	}
	
	@RequestMapping(value="delRole/{roleid}",method=RequestMethod.POST)
	public @ResponseBody String delRole(@PathVariable String roleid){
		try {
			rolelogService.delRole(roleid);
			return "ok";
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
	}
	/* 获取资源列表*/
	@RequestMapping(value="getAllSectForRole/{roleid}",method=RequestMethod.POST)
	public void getAllSectForRole(@PathVariable String roleid,HttpServletResponse response){
		List<Map<String,Object>> list = rolelogService.getAllSectForRole(roleid);  //查询除了模块级的所有资源
		List<TGroup> groupList = srService.getAllGroup();
		Map<String,String> gMap = new HashMap<String, String>();
		for(int i=0,length=groupList.size();i<length;i++){
			TGroup group = groupList.get(i);
			gMap.put(group.getId(), group.getTitle());
		}
		List<Map<String,Object>> jsonList = new ArrayList<Map<String,Object>>();
		Map<String,Object> json = null;
		if(list!=null && !list.isEmpty()){
			Set<String> strSet = new HashSet<String>();
			for(Map<String,Object> map : list){
				json = new HashMap<String, Object>();
				json.put("id", map.get("ID").toString());
				json.put("pid", map.get("PID").toString());
				json.put("groupid", map.get("GROUP_ID").toString());
				json.put("_parentId", "0".equals(map.get("PID").toString())?map.get("GROUP_ID").toString():map.get("PID").toString());
				json.put("sectname",  map.get("SECTNAME")!=null?map.get("SECTNAME").toString():null);
				json.put("comments",  map.get("COMMENTS").toString());
				json.put("remark", map.get("REMARK")!=null ? map.get("REMARK").toString() : "");
				json.put("slevel", map.get("SLEVEL")!=null?map.get("SLEVEL").toString():"");
				json.put("status", map.get("STATUS")!=null ? map.get("STATUS").toString() : "");
				json.put("sort", map.get("SORT")!=null ? map.get("SORT").toString() : "");
				json.put("icon", map.get("ICON")!=null ? map.get("ICON").toString() : "");
				json.put("upttime", map.get("UPDATETIME")!=null ? map.get("UPDATETIME").toString() : "---");
				json.put("version", map.get("VERSION")!=null ? map.get("VERSION").toString() : "");
				json.put("chked", map.get("SECT_ID")==null?"0":"1");
				strSet.add(map.get("GROUP_ID").toString());
				jsonList.add(json);
			}
			for(String str : strSet){
				json = new HashMap<String, Object>();
				json.put("id", str);json.put("comments", gMap.get(str));json.put("chked", "-1");
				jsonList.add(json);
			}
		}
		Map<String,Object> responseJSON = new HashMap<String, Object>();
		responseJSON.put("total", jsonList.size());
		responseJSON.put("rows", jsonList);
		Httptear.ResponseResultByUTF8(JsonUtils.objectToJson(responseJSON), response);
	}
	/*  为角色分配资源*/
	@RequestMapping(value="addSect2Role",method=RequestMethod.POST)
	public @ResponseBody String addSect2Role(String roleid,String sectid){
		if(StringUtils.isEmpty(roleid) || StringUtils.isEmpty(sectid)){
			return Escape.escape("{success:0,msg:'错误的POST参数'}");
		}
		try {
			if(rolelogService.chkRoleSect(roleid, sectid)){
				return Escape.escape("{success:0,msg:'重复操作，您已添加该资源。'}");
			}
			TRole role = rolelogService.getRole(roleid);
			if(role==null){
				return Escape.escape("{success:0,msg:'角色信息不存在'}");
			}
			TSect sect = srService.getSect(sectid);
			if(sect==null){
				return Escape.escape("{success:0,msg:'资源信息不存在'}");
			}
			if(!"0".equals(sect.getPid()) && !rolelogService.chkRoleSect(roleid,sect.getPid())){
				return Escape.escape("{success:0,msg:'请先添加父级资源'}");
			}
			rolelogService.addSectInRole(roleid, sectid);
			PmcSecurityMetadataSource pmcMetadataSource = new PmcSecurityMetadataSource(userService);
			pmcMetadataSource.loadResourcesDefine();
			return Escape.escape("{success:1,msg:'["+sect.getComments()+"]已成功分配给["+role.getComments()+"]！'}");
		} catch (Exception e) {
			e.printStackTrace();
			return Escape.escape("{success:0,msg:'"+e.getMessage()+"'}");
		}
	}
	/* 删除角色关联的资源*/
	@RequestMapping(value="delSectFromRole",method=RequestMethod.POST)
	public @ResponseBody String delSectFromRole(String roleid,String sectid){
		if(StringUtils.isEmpty(roleid) || StringUtils.isEmpty(sectid)){
			return Escape.escape("{success:0,msg:'错误的POST参数'}");
		}
		try {
			if(!rolelogService.chkRoleSect(roleid, sectid)){
				return Escape.escape("{success:0,msg:'重复操作，您已删除该资源。'}");
			}
			TRole role = rolelogService.getRole(roleid);
			if(role==null){
				return Escape.escape("{success:0,msg:'角色信息不存在'}");
			}
			TSect sect = srService.getSect(sectid);
			if(sect==null){
				return Escape.escape("{success:0,msg:'资源信息不存在'}");
			}
			rolelogService.delRoleSectById(roleid, sectid);
			PmcSecurityMetadataSource pmcMetadataSource = new PmcSecurityMetadataSource(userService);
			pmcMetadataSource.loadResourcesDefine();
			return Escape.escape("{success:1,msg:'["+sect.getComments()+"]已从角色["+role.getComments()+"]中删除！'}");
		} catch (Exception e) {
			e.printStackTrace();
			return Escape.escape("{success:0,msg:'"+e.getMessage()+"'}");
		}
	}
	
/*------------------------------------日志管理-------------------------------------*/
	@RequestMapping(value="getAllOperLog",method={RequestMethod.POST})
	public @ResponseBody JsonGrid<TSysoperLog> getAllOperLog(
			@RequestParam(required=true) Integer page,
			@RequestParam(required=true) Integer rows,
			String queryField,String queryValue, //@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
			Timestamp btime,Timestamp etime){
		StringBuffer strSql = new StringBuffer();
		if(StringUtils.isNotEmpty(queryField) && DEFAULT_LOG_FIELD.indexOf(queryField) != -1 && StringUtils.isNotEmpty(queryValue)){
			strSql.append(" and " + Util.separateValidWord(DEFAULT_LOG_FIELD,queryField) + " like '%"+ queryValue +"%'");
		}
		if(btime!=null && etime!=null){
			strSql.append(" and OPER_TIME between ? and ?");
		}
		PaginationSupport<TSysoperLog> pager = rolelogService.getAllOperLog(strSql.toString(), page, rows,btime,etime);
		return new JsonGrid<TSysoperLog>(pager);
	}
	@RequestMapping(value="getOperLog/{logid}",method={RequestMethod.GET})
	public @ResponseBody TSysoperLog getOperLog(@PathVariable String logid){
		TSysoperLog syslog = rolelogService.getOperLog(logid);
		return syslog==null ? new TSysoperLog() :syslog;
	}
	/* 删除日志*/
	@RequestMapping(value="delOperLogById/{logid}",method={RequestMethod.POST})
	public @ResponseBody String delOperLogById(@PathVariable String logid){
		try {
			rolelogService.delOperLogById(logid);
			return "ok";
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
	}
	/* 清空日志记录*/
	@RequestMapping(value="delAllOperLog",method={RequestMethod.POST})
	public @ResponseBody String delAllOperLog(){
		try {
			rolelogService.delAllOperLog();
			return "ok";
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
	}
}
